package com.my.study.common.security.account;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 账号密码登录过滤器
 * 
 * @author yidujun
 * @date 2022/8/3 17:08
 */
@Slf4j
public class AccountAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "userName";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
    
    public AccountAuthenticationProcessingFilter() {
        super(new AntPathRequestMatcher("/account/login", "POST"));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);
    }
    
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String method = request.getMethod();
        if (!"POST".equalsIgnoreCase(method)) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        String userName = obtainUsername(request);
        String password = obtainPassword(request);
        
        if (null == userName) {
            throw new IllegalArgumentException("userName is null.");
        }
        
        if (null == password) {
            throw new IllegalArgumentException("password is null.");
        }

        AccountAuthenticationToken authenticationToken = new AccountAuthenticationToken(userName, password);

        return this.getAuthenticationManager().authenticate(authenticationToken);
    }


    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(SPRING_SECURITY_FORM_USERNAME_KEY);
    }

    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(SPRING_SECURITY_FORM_PASSWORD_KEY);
    }
}
